package com.xinyu.controller;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import com.xinyu.vo.BaseResult;
import com.xinyu.vo.PositionLogData;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("positionLog")
public class PositionLogController {

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));

            // 读取前两行获取标题信息
            String firstLine = reader.readLine();
            String secondLine = reader.readLine();
            String[] firstLineParts = firstLine.split("\t");
            String[] secondLineParts = secondLine.split("\t");

            // 构建标题
            String title = String.format("%s(%s: %s; %s: %s)",
                    file.getOriginalFilename(),
                    firstLineParts[0], firstLineParts[1],
                    secondLineParts[0], secondLineParts[1]);

            // 跳过空行
            reader.readLine();

            // 读取列名行
            String headerLine = reader.readLine();
            String[] headers = headerLine.split("\t");

            // 移除Time列，保留其他列名
            List<String> columnList = new ArrayList<>(Arrays.asList(headers));
            columnList.remove(0); // 移除第一列 (Time)

            // 读取数据并按列组织
            Map<String, List<Double>> columnData = new HashMap<>();
            for (String column : columnList) {
                columnData.put(column, new ArrayList<>());
            }

            String line;
            while ((line = reader.readLine()) != null && !line.trim().isEmpty()) {
                String[] values = line.split("\t");
                if (values.length != headers.length) continue;

                // 从第二列开始处理数据（跳过Time列）
                for (int i = 1; i < values.length; i++) {
                    String column = headers[i];
                    try {
                        double value = Double.parseDouble(values[i]);
                        columnData.get(column).add(value);
                    } catch (NumberFormatException e) {
                        columnData.get(column).add(0.0);
                    }
                }
            }

            Map<String, Object> response = new HashMap<>();
            response.put("title", title);
            response.put("columns", columnList);
            response.put("columnData", columnData);

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to process file: " + e.getMessage());
        }
    }
}